$(()=>{
    var sendTxt = $('#sendtxt');
    var sendbt = $('#sendbt');
    var chatf = $('#ChatF');
    var msg_num = 0;

    sendTxt.on('keydown',e=>{
        if(e.key === "Enter"){
            sendText_fn();
        }
    })
    sendbt.on('click',e=>{
        sendText_fn();
    })

    function sendText_fn(){
        let txt = sendTxt.val();
        $.ajax({
            type:'get',
            url:`/chat?msg=${txt}`,
            success:function(e){
                console.log(e);
                if(e.data.result){
                    sendTxt.val('');
                }else{
                    alert('消息发送失败，请检查')
                }
            }
        })
    }
    function receive(){
        //接受消息
        $.ajax({
            type:'get',
            url:`/getmsg?msg_num=${msg_num}`,
            success:function(e){
                if(e.data.result){
                    appendTxt(e.data.data);
                }else{
                    setTimeout(()=>{
                        receive();
                    },500)
                }
            }
        })

    }
    function appendTxt(data){
        let msgs = (data+"").split('&');
        chatf.append(`   <div class="themsg">
            <div class="name">${msgs[0]}</div>
            <div class="msg">${msgs[1]}</div>
            <div class="time">${msgs[2]}</div>
            </div>`)
            $('#ChatF').prop('scrollTop',$('#ChatF').prop('scrollHeight'));
        setTimeout(()=>{
            receive()
        },500)

    }

    console.log("开始接受消息");
})